package org.ash.socket.bio;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 单线程阻塞版本
 * 1. 同一时间只能有一个客户端连接上来
 * @author Ashin
 */
public class ServerSocketSingleThreadDemo {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);

        while (true) {
            System.out.println("等待连接");
            //阻塞
            Socket socket = serverSocket.accept();
            System.out.println("连接成功..." + socket);

            handleSocket(socket);
        }
    }

    public static void handleSocket(Socket socket) throws IOException {
        byte[] bytes = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        //这里会阻塞
        int len = bis.read(bytes);

        if (len != -1) {
            System.out.println("接收到客户端数据:" + new String(bytes, 0, len));
        }

        socket.getOutputStream().write("I receive".getBytes());
        socket.getOutputStream().flush();

        socket.close();
        System.out.println("连接关闭..." + socket);
    }
}
